/**
 *
 * Copyright 2009 Bill Garrett (memesis@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 * this file except in compliance with the License.  You may obtain a copy of the
 * License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License. 
 */
package org.memesis.pandorasbook;

import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * This class is responsible for generating a StorybookApplet object from a URL,
 * whose presumed contents are an XML document describing the applet.
 *
 * @author garrett
 */
public class PandoraAppletFactory {
	public static PandoraApplet createApplet(URL appletDescription, PandoraDesktop desktop) throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = db.parse(appletDescription.openStream());
		
		NodeList list = doc.getElementsByTagName("applet");
		Node n;

		if(list.getLength() != 1) {
			// TODO: throw exception
			return null;
		}
		
		String appletType = list.item(0).getAttributes().getNamedItem("type").getNodeValue();
		PandoraApplet applet = initializeAppletFromType(appletType);
		
		applet.setDesktop(desktop);
		
		list = doc.getElementsByTagName("property");
		for(int i = 0; i < list.getLength(); i++) {
			n = list.item(i);
			applet.getProperties().put(n.getAttributes().getNamedItem("name").getNodeValue(), n.getAttributes().getNamedItem("value").getNodeValue());  
		}
		
		applet.getProperties().put("pandorasbook-applet-url", appletDescription.toString());
		
		return applet;
	}
	
	private static PandoraApplet initializeAppletFromType(String appletType) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class<?> clazz = Class.forName("org.memesis.pandorasbook." + appletType);
		return (PandoraApplet) clazz.newInstance();
	}
}
